package com.gitee.huanminabc.db_freedom.interceptor;

import com.baomidou.mybatisplus.core.MybatisParameterHandler;
import com.gitee.huanminabc.db_freedom.wrapper.AbstractBaseWrapper;
import com.gitee.huanminabc.db_freedom.wrapper.LambdaSQL;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.util.Properties;

@Intercepts({@Signature(
        type = StatementHandler.class,
        method = "prepare",
        args = {Connection.class, Integer.class}
), @Signature(
        type = StatementHandler.class,
        method = "getBoundSql",
        args = {}
), @Signature(
        type = Executor.class,
        method = "update",
        args = {MappedStatement.class, Object.class}
), @Signature(
        type = Executor.class,
        method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
), @Signature(
        type = Executor.class,
        method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}
)})
public class FreedomInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        Object target = invocation.getTarget();
        if (target instanceof Executor) {
            final Executor executor = (Executor) target;
            if (args[0] instanceof MappedStatement) {
                if (args[1] instanceof AbstractBaseWrapper) {
                    MappedStatement ms = (MappedStatement) args[0];
                    Object parameter = args[1];
                    if (ms.getSqlCommandType() == SqlCommandType.SELECT) {
                        LambdaSQL lambdaSQL = (LambdaSQL) parameter;
                        BoundSql boundSql = ms.getBoundSql(parameter);
                        //修改入参的sql
                        updateBoundSql(lambdaSQL, boundSql);
                        RowBounds rowBounds = (RowBounds) args[2];
                        CacheKey cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
                        return executor.query(ms, parameter, (RowBounds) args[2], (ResultHandler) args[3], cacheKey, boundSql);

                    }
                }
            }
        }
        if (target instanceof StatementHandler) {
            StatementHandler sh = (StatementHandler) target;
            MybatisParameterHandler parameterHandler = (MybatisParameterHandler) sh.getParameterHandler();
            Field sqlCommandType1 = parameterHandler.getClass().getDeclaredField("sqlCommandType");
            sqlCommandType1.setAccessible(true);
            SqlCommandType sqlCommandType = (SqlCommandType) sqlCommandType1.get(parameterHandler);
            if (sqlCommandType != SqlCommandType.SELECT) {
                Field boundSql1 = parameterHandler.getClass().getDeclaredField("boundSql");
                boundSql1.setAccessible(true);
                BoundSql boundSql = (BoundSql) boundSql1.get(parameterHandler);
                LambdaSQL lambdaSQL = (LambdaSQL) parameterHandler.getParameterObject();
                //判断是否有
                updateBoundSql(lambdaSQL, boundSql);
            }
        }
        return invocation.proceed();
    }

    private  void  updateBoundSql(LambdaSQL lambdaSQL, BoundSql boundSql) {
        Class<? extends BoundSql> aClass = boundSql.getClass();
        try {
            Field fsql = aClass.getDeclaredField("sql");
            fsql.setAccessible(true);
            fsql.set(boundSql, lambdaSQL.SQL().toString());
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }



    @Override
    public Object plugin(Object target) {
        return Interceptor.super.plugin(target);
    }

    @Override
    public void setProperties(Properties properties) {
        Interceptor.super.setProperties(properties);
    }
}